package com.ainiyar.springweb.config.web;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**************************************
 * File Name : WebConfigurer
 * Created with : IntelliJ IDEA.
 * Author : 艾尼亚尔·毛拉吾提
 * QQ : 524155792  WeChat : ainiyar0124
 * Created Time : 2024/2/4  12:47
 * Desc :web配置类
 ***************************************/
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
    @Resource
    private WebPrefix webPrefix;

    /**
     * 前缀处理
     * @param configurer 配置
     */
    public void configurePathMatch(PathMatchConfigurer configurer){
        // 根据不同包匹配表达式，添加各自的统一前缀
        configurePathMatch(configurer, webPrefix.getAdmin());
        configurePathMatch(configurer, webPrefix.getApplet());
    }
    private void configurePathMatch(PathMatchConfigurer configurer, WebPrefix.Api api){
        // 创建路径匹配类，指定以'.'分隔
        AntPathMatcher antPathMatcher = new AntPathMatcher(".");
        // 指定匹配前缀
        // 满足：类上有RestController注解 && 该类的包名匹配指定的自定义包的表达式
        configurer.addPathPrefix(api.getPrefix(), clazz -> clazz.isAnnotationPresent(RestController.class)
                && antPathMatcher.match(api.getControllerPath(), clazz.getPackage().getName()));
    }
    //处理跨域
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") //允许所有请求访问
                .allowedMethods("*") //允许所有的请求方法访问该跨域资服务
                .allowedOrigins("*")//允许所有的请求域名访问我们的跨域资源
                .allowedHeaders("*");//允许所有的请求Header访问
    }
}

